//
//  SearchViewController.m
//  HCSortAndSearchDemo
//
//  Created by Caoyq on 16/3/28.
//  Copyright © 2016年 Caoyq. All rights reserved.
//

#import "BCSearchViewController.h"
#import "ZYPinYinSearch.h"
#import "HCSortString.h"
#import "UIAlertView+Blocks.h"
#import "SVProgressHUD.h"
#import "MJRefresh.h"
#import "CommonFunc.h"
#import "BarCode-Swift.h"

#define kColor          [UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1];

@interface BCSearchViewController ()<UISearchResultsUpdating>

@property (strong, nonatomic) UISearchController *searchController;
@property (strong, nonatomic) NSArray *dataSource;/**<排序前的整个数据源*/
@property (strong, nonatomic) NSDictionary *allDataSource;/**<排序后的整个数据源*/
@property (strong, nonatomic) NSMutableArray *searchDataSource;/**<搜索结果数据源*/
@property (strong, nonatomic) NSArray *indexDataSource;/**<索引数据源*/

@end

@implementation BCSearchViewController

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title = @"人员";
    [self setNavigationItem];
    [self initData];
    self.tableView.backgroundColor = kColor;
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    self.tableView.sectionIndexColor = [UIColor colorWithRed:1.0 / 255.0 green:170 / 255.0 blue:235.0 / 255.0 alpha:1.0];
    [self.tableView setTableHeaderView:self.searchController.searchBar];
    self.tableView.rowHeight = 56;
    //增加下拉刷新控件
    [self addPullRefreshControl];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear: animated];
    self.searchController.active = NO;
    [self.tableView reloadData];

}
- (void)dealloc {
    _searchController = nil;
    self.tableView = nil;
}

#pragma mark - Init
- (void)initData {
    _searchDataSource = [NSMutableArray new];
    NSArray *searchResults = [Bridge2OC getUserList];
    if (searchResults && searchResults.count > 0) {
        _dataSource = searchResults.copy;
        _allDataSource = [HCSortString sortAndGroupForArray:_dataSource PropertyName:@"full_name"];
        _indexDataSource = [HCSortString sortForStringAry:[_allDataSource allKeys]];
    } else {
        [SVProgressHUD show];
        [CommonFunc getUsersWithResult:^(id results, int status) {
            [SVProgressHUD dismiss];
            if (status == 1 && [results isKindOfClass:[NSArray class]]) {
                _dataSource = results;
                _allDataSource = [HCSortString sortAndGroupForArray:_dataSource PropertyName:@"full_name"];
                _indexDataSource = [HCSortString sortForStringAry:[_allDataSource allKeys]];
                [self.tableView reloadData];
            } else {
                [SVProgressHUD showErrorWithStatus:results];
            }
        }];
    }
}

- (void)addPullRefreshControl {
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (!self.searchController.active) {
            [CommonFunc getUsersWithResult:^(id results, int status) {
                if(status == 1 && [results isKindOfClass:[NSArray class]]) {
                    _dataSource = results;
                    _allDataSource = [HCSortString sortAndGroupForArray:_dataSource PropertyName:@"full_name"];
                    _indexDataSource = [HCSortString sortForStringAry:[_allDataSource allKeys]];
                    [self.tableView reloadData];
                    [self.tableView.mj_header endRefreshing];
                } else {
                    [SVProgressHUD showErrorWithStatus:results];
                }
            }];
        } else {
            [self.tableView.mj_header endRefreshing];
        }
    }];
}

- (UISearchController *)searchController {
    if (!_searchController) {
        _searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
        _searchController.searchResultsUpdater = self;
        _searchController.dimsBackgroundDuringPresentation = NO;
        _searchController.hidesNavigationBarDuringPresentation = YES;
        self.definesPresentationContext = YES;
        _searchController.searchBar.placeholder = @"输入姓名/工号/部门搜索";
        [_searchController.searchBar sizeToFit];
    }
    return _searchController;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (!self.searchController.active) {
        return _indexDataSource.count;
    }else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!self.searchController.active) {
        NSArray *value = [_allDataSource objectForKey:_indexDataSource[section]];
        return value.count;
    }else {
        return _searchDataSource.count;
    }
}
//头部索引标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (!self.searchController.active) {
        return _indexDataSource[section];
    }else {
        return nil;
    }
}
//右侧索引列表
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (!self.searchController.active) {
        return _indexDataSource;
    }else {
        return nil;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"CellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        UILabel *depLabel = [[UILabel alloc] init];
        depLabel.tag = 2017 + indexPath.section * 1000 + indexPath.row;
        depLabel.textColor = [UIColor lightGrayColor];
        depLabel.font = [UIFont systemFontOfSize:12];
        [cell addSubview:depLabel];
        depLabel.translatesAutoresizingMaskIntoConstraints = NO;
        // 添加 width 约束
        NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:depLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:220];
        [depLabel addConstraint:widthConstraint];
        // 添加 height 约束
        NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:depLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:12];
        [depLabel addConstraint:heightConstraint];
        // 添加 right 约束
        NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:depLabel attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeRight multiplier:1.0 constant:-12];
        [cell addConstraint:rightConstraint];
        // 添加 bottom 约束
        NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:depLabel attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-12];
        [cell addConstraint:bottomConstraint];
    }
    
    UIView *view = [cell viewWithTag:(2017 + indexPath.section * 1000 + indexPath.row)];
    UILabel *tmpLabel = nil;
    if (view && [view isKindOfClass:[UILabel class]]) {
        tmpLabel = (UILabel *)view;
    }
    
    if (!self.searchController.active) {
        NSArray *value = [_allDataSource objectForKey:_indexDataSource[indexPath.section]];
        cell.textLabel.text = [value[indexPath.row] full_name];
        if ([value[indexPath.row] staff_code]) {
            cell.detailTextLabel.text = [NSString stringWithFormat: @"工号：%@",[value[indexPath.row] staff_code]];
        }
        if ([value[indexPath.row] user_name]) {
            tmpLabel.text = [NSString stringWithFormat: @"部门：%@",[value[indexPath.row] user_name]];
        }
    }else{
        cell.textLabel.text = [_searchDataSource[indexPath.row] full_name];
        if ([_searchDataSource[indexPath.row] staff_code]) {
            cell.detailTextLabel.text = [NSString stringWithFormat: @"工号：%@",[_searchDataSource[indexPath.row] staff_code]];
        }
        if ([_searchDataSource[indexPath.row] user_name]) {
            tmpLabel.text = [NSString stringWithFormat: @"部门：%@",[_searchDataSource[indexPath.row] user_name]];
        }
    }
    cell.detailTextLabel.textColor = [UIColor lightGrayColor];
    cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"unCheckMark"]];
    
    return cell;
}
//索引点击事件
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    return index;
}

#pragma mark - Table View Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    User *people = nil;
    if (!self.searchController.active) {
        NSArray *value = [_allDataSource objectForKey:_indexDataSource[indexPath.section]];
        self.block(value[indexPath.row]);
        people = value[indexPath.row];
    }else{
        self.block(_searchDataSource[indexPath.row]);
        people = _searchDataSource[indexPath.row];
    }
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkMark"]];
    
    [Common setPersonWithPerson:people];
    if([Common isHasQRCode]) {
        NSString *msg = [NSString stringWithFormat:@"确认要绑定【%@】和扫码信息？",people.full_name];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:msg
                                               cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:^{
            [Common clearGlobalTuples];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }]
                                               otherButtonItems:[RIButtonItem itemWithLabel:@"绑定" action:^{
            [SVProgressHUD show];
            [CommonFunc findGoodsName:[Common getGlobalGoodsCode] Block:^(id results, int status) {
                if (status == 1) {
                    if (results == nil) {
                        [SVProgressHUD showErrorWithStatus:@"此商品暂无库存"];
                        return;
                    }
                    [CommonFunc bind:[Common getGlobalPersonUserId] FullName:people.full_name Department:people.user_name Code:[Common getGlobalGoodsCode] GoodsName:[results objectForKey:@"goods_name"] Block:^(id result, int status) {
                        [SVProgressHUD dismiss];
                        if (status == 1) {
                            [SVProgressHUD showSuccessWithStatus:@"绑定成功"];
                            [CommonFunc updateStockCountsWithGoodsId:[results objectForKey:@"goods_code"] Block:^(id results, int status) {
                                if (status == 0) {
                                    [SVProgressHUD showErrorWithStatus:results];
                                }
                            }];
                        } else {
                            [SVProgressHUD showErrorWithStatus:result];
                        }
                        [Common clearGlobalTuples];
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    }];
                }
            }];

        }], nil];
        [alert show];
    } else {
        [SVProgressHUD showInfoWithStatus:@"人员已选，开始扫码"];
        [SVProgressHUD dismissWithDelay:1.0];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            BCScanViewController *scanVC = [[BCScanViewController alloc] init];
            [self.navigationController pushViewController:scanVC animated:YES];
        });
    }
}

#pragma mark - UISearchDelegate
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    [_searchDataSource removeAllObjects];
    NSArray *ary = [HCSortString getAllValuesFromDict:_allDataSource];
   
    if (searchController.searchBar.text.length == 0) {
        [_searchDataSource addObjectsFromArray:ary];
    } else {
        NSArray *ary1 = [ZYPinYinSearch searchWithOriginalArray:ary andSearchText:searchController.searchBar.text andSearchByPropertyName:@"full_name"];
        NSArray *ary2 = [ZYPinYinSearch searchWithOriginalArray:ary andSearchText:searchController.searchBar.text andSearchByPropertyName:@"staff_code"];
        NSArray *ary3 = [ZYPinYinSearch searchWithOriginalArray:ary andSearchText:searchController.searchBar.text andSearchByPropertyName:@"user_name"];
        [_searchDataSource addObjectsFromArray:ary1];
        [_searchDataSource addObjectsFromArray:ary2];
        [_searchDataSource addObjectsFromArray:ary3];
    }
    [self.tableView reloadData];
}

#pragma mark - block
- (void)didSelectedItem:(SelectedItem)block {
    self.block = block;
}

- (void)searchResult: (UISearchController *)searchController {
//    NSPredicate *precidate = [NSPredicate predicateWithFormat:@"displayName CONTAINS[cd] %@", searchController.searchBar.text];
    
}

#pragma -mark left bar item
- (void)setNavigationItem {
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
    barItem.image = [UIImage imageNamed:@"backBtnU"];
    
    //用于消除左边空隙，要不然按钮顶不到最前面
    UIBarButtonItem *spacer = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    spacer.width = 8;
    self.navigationItem.leftBarButtonItems = @[spacer, barItem];
}

- (void)backAction:(id)sender {
    if([self.pageFrom isEqualToString:@"Main"]) {
        [Common customPopAnimationFromNavigationWithNav:self.navigationController type:@"cube" subType:kCATransitionFromRight duration:0.5];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

@end
